package com.kuangchi.test.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Base64;

import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class IamgeIdUtil {

    private static final int FILE_ID_LEGTH = 32;

    private static final Logger logger = LoggerFactory.getLogger(IamgeIdUtil.class);

    //图片到byte数组
    public static byte[] image2byte(String path) {
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (FileNotFoundException e) {
            logger.error("image2byte FileNotFoundException", e);
        } catch (IOException e) {
            logger.error("image2byte IOException", e);
        }
        return data;
    }

    // byte数组到图片
    public static void byte2image(byte[] data, String path) {
        if (data.length < 3 || path.equals(""))
            return;
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
        } catch (Exception e) {
            logger.error("byte2image Exception", e);
        }
    }

    public static byte[] byteAddId(byte[] img_byte, String id) {
        byte[] id_byte = id.getBytes();
        byte[] result_byte = new byte[img_byte.length + id_byte.length];
        System.arraycopy(img_byte, 0, result_byte, 0, img_byte.length);
        System.arraycopy(id_byte, 0, result_byte, img_byte.length, id_byte.length);
        return result_byte;
    }

    public static String byte2base64(byte[] img_byte, String id) {
        byte[] result_byte = byteAddId(img_byte, id);
        return Base64.getEncoder().encodeToString(result_byte);
    }

    public static String byteGetId(byte[] img_byte) {
        byte[] id_byte = new byte[FILE_ID_LEGTH];
        System.arraycopy(img_byte, img_byte.length - FILE_ID_LEGTH, id_byte, 0, FILE_ID_LEGTH);
        return new String(id_byte);
    }

    public static String byteGetId(String imgPath) {
        byte[] img_byte = image2byte(imgPath);
        return byteGetId(img_byte);
    }

}
